package org.example.coknown.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.coknown.common.R;
import org.example.coknown.entity.TraceabilityInformation;
import org.example.coknown.service.TraceabilityInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 溯源信息上传，查询
*/
@Slf4j
@RestController
@RequestMapping("/informations")
public class TraceabilityInformationController {

    @Autowired
    private TraceabilityInformationService traceabilityInformationService;

    /**
     * 分页查询溯源信息
     */
    @GetMapping
    public R<IPage<TraceabilityInformation>> getTraceabilityInformation(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page, @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if(page == null) page = 1;
        if(pageSize == null) pageSize = 10;
        IPage<TraceabilityInformation> traceabilityPage = traceabilityInformationService.listUsers(page, pageSize);
        log.info("分页查询成功{}",traceabilityPage);
        return R.success(traceabilityPage);
    }
    /**
     * 根据id查询溯源信息
     */
    @GetMapping("/{id}")
    public R<List<TraceabilityInformation>> SelectById(@PathVariable Integer id){
        List<TraceabilityInformation> listTraceabilityInformation = traceabilityInformationService.selectById(id);

        log.info("查询产品成功id:{}",id);
        return R.success(listTraceabilityInformation);
    }
    /**
     * 添加溯源信息
     */
    @PostMapping("/add")
    public R<TraceabilityInformation> addTraceabilityInformation(@RequestBody TraceabilityInformation traceabilityInformation){
        traceabilityInformationService.addTraceabilityInformation(traceabilityInformation);

        log.info("添加溯源信息成功{}",traceabilityInformation);
        return R.success(null);
    }
    /**
     * 根据id查询溯源信息，成功返回查询信息，失败返回null
     */
    @GetMapping("/betch/{betch}")
    public R<List<TraceabilityInformation>> selectByBetch(@PathVariable Integer betch){
        List<TraceabilityInformation> listTraceabilityInformation = traceabilityInformationService.selectByBetch(betch);

        if (listTraceabilityInformation.isEmpty()){
            log.info("查询产品失败betch:{}",betch);
            return R.error("无产品信息");
        }
        log.info("查询产品成功betch:{},{}",betch,listTraceabilityInformation);
        return R.success(listTraceabilityInformation);
    }

}
